import React, { useRef, useState } from "react";

import StoTable, { StoTableApi } from "../components/StoTable/StoTable";
import StoPaginator, { StoPaginatorApi } from "../components/StoPaginator/StoPaginator";

import { getStudents } from "../common/mockdata";
import StoFilter from "../components/StoFilter/StoFilter";

let totalPages = 20
let currentPage = 1;
const allStudents = getStudents(totalPages);
const pageSize = 10;

const formatter = {
  avatar: (student: any) => (
    <a href={`/${student.id}`}>
      <img src={student.avatar} alt="" />
    </a>
  ),

  name: (student: any) => (
    <a style={{ fontWeight: "bold" }} href={`/${student.id}`}>
      {student.name}
    </a>
  ),
};

const filters = [
  {
    type: "text",
    placeholder: "请输入用芳名",
    key: "name",
  },

  {
    type: "select",
    options: ["男", "女", "死变态", "二椅子"],
    placeholder: "请选择性别",
    key: "gender",
  },

  {
    type: "number",
    placeholder: "年龄",
    key: "age",
  },
];

const onReset = () => {
  console.log("用户点击了重置");
};

export default function TableXXDemo() {
  const tableRef = useRef<StoTableApi>(null);
  const paginatorRef = useRef<StoPaginatorApi>(null);
  // console.log("_students",_students);

  const [students, setStudents] = useState(allStudents);

  const onSearchResult = (filteredData: Record<string, any>[]) => {
    console.log("用户点击了搜索", filteredData);
    setStudents([...filteredData]);
    paginatorRef.current?.turnToPage(1)
  };

  return (
    <div style={{width:1200}}>
      <h3>
        TableXXDemo:
        <button
          onClick={() =>
            setStudents([...students.filter((s) => s.gender === "女")])
          }
        >
          setStudents
        </button>
      </h3>

      <StoFilter
        allData={allStudents}
        data={students}
        filters={filters}
        onReset={onReset}
        onSearchResult={onSearchResult}
      ></StoFilter>

      <StoTable
        ref={tableRef}
        data={students}
        pageSize={10}
        sortableKeys={["id", "name", "age", "gender"]}
        formatter={formatter}
        currentPage={1}
      ></StoTable>

      <StoPaginator
        ref={paginatorRef}
        totalPages={Math.ceil(students.length / pageSize)}
        currentPage={currentPage}
        onPageChange={(n: number) => {
          console.log("onPageChange", n)
          tableRef.current?.turnToPage(n)
        }}
      ></StoPaginator>


    </div>
  );
}
